﻿using CommunicationLib.Model;
using PLCdev.Model;
using PlcLib;
using PlcLib.Model;
using PlcLib.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCdev.ViewModel
{
    internal class MainViewModel : ObservableObject
    {
        /// <summary>
        /// 属性才可以绑定到xmal前端
        /// </summary>
        public OrmonPlc OrmonPlc { get; set; } = new OrmonPlc();

        private ObservableCollection<Message> messageList  = new ObservableCollection<Message>();
        public ObservableCollection<Message> MessageList
        {
            get { return messageList; }
            set
            {
                messageList = value;
                RaisePropertyChanged(nameof(MessageList));
            }
            
        }

        private ObservableCollection<Message> byteList = new ObservableCollection<Message>();
        public ObservableCollection<Message> ByteList
        {
            get { return byteList; }
            set
            {
                byteList = value;
                RaisePropertyChanged(nameof(ByteList));
            }

        }

        public MainViewModel()
        {
            OrmonPlc.OnError += OrmonPlc_OnMessage;
            OrmonPlc.OnMessage += OrmonPlc_OnMessage;
            // 使用 MainViewModel 中的 PLC 实例
            OrmonPlc.OnSend += OrmonPlc_OnSend;
            OrmonPlc.OnReceived += OrmonPlc_OnReceived;
        }

        private void OrmonPlc_OnReceived(object arg1, DataPackage package)
        {
            Message message = new Message()
            {
                DateTime = package.ReceiveTime,
                Content = "接收：" + package.ReceiveBufferToString
            };

            App.Current.Dispatcher.Invoke(() =>
            {

                byteList.Insert(0, message);//在集合的开头插入新消息
            });//在UI线程中更新集合
        }

        private void OrmonPlc_OnSend(object arg1, DataPackage package)
        {
            Message message = new Message()
            {
                DateTime = package.SendTime,
                Content = "下发："+ package.SendBufferToString
            };
       
            App.Current.Dispatcher.Invoke(() =>
            {

                byteList.Insert(0, message);//在集合的开头插入新消息
            });//在UI线程中更新集合
        }

        private void OrmonPlc_OnMessage(object sender, PlcEventArgs arg)
        {
           Message message = new Message()
            {
                DateTime = DateTime.Now,
                Content = arg.Message
            };
            if(arg.Exception != null)//如果有异常信息
            {
                message.Content += "\r\n" + arg.Exception.ToString();//换行显示异常信息
            }
            App.Current.Dispatcher.Invoke(() =>
            {
                
                messageList.Insert (0, message);//在集合的开头插入新消息
            });//在UI线程中更新集合
        }

     
    }
}
